from flask_login import logout_user, current_user
from forms.login_form import LoginForm
from routes import app
from flask import render_template, abort, redirect, url_for, flash
from services.user_service import UserService
from flask import Flask, request, jsonify

@app.route('/test/login', methods=['GET', 'POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    # 在这里进行用户名密码的验证，可以连接数据库进行验证或者使用硬编码的方式验证
    # 这里只是一个示例，实际中需要根据你的情况来实现

    user = UserService().do_login(username=username, password=password)
    print("test/login user", user)
    if user:
        return jsonify({'message': 'Login successful'}), 200
    else:
        return jsonify({'message': 'Invalid credentials'}), 401


# 用表单传输数据，有些问题
@app.route('/user/login', methods=['GET', 'POST'])
def login_page():
    # 检查是否是登录的用户，利用Flask-Login
    if current_user.is_authenticated:
        return redirect('http://localhost:3030/#/login')

    form = LoginForm()
    # print("前端输入：", form.username.data, password=form.password.data)
    if form.validate_on_submit():
        print("form.validate_on_submit()")
        user = UserService().do_login(username=form.username.data, password=form.password.data)

        if user:
            print("if user:")
            #  login_user(admin, remember)  记住登录的状态，该怎么调整，需要哪些参数？
            # flash(f'欢迎{form.username.data}回来', category='success')
            response = {
                "message": "Login successful",
                "user": {
                    "id": user.id,
                    "username": user.username,
                    # 其他需要返回的用户信息
                }
            }
            return jsonify(response), 200
        else:
            return jsonify({"message": "Invalid username or password."}), 401
    else:
        return jsonify({"message": "Invalid form data无效的数据."}), 400


@app.route('/user/logout')
def logout_page():
    logout_user()
    return redirect(url_for('home_page'))

